#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>
#include <pthread.h>

int x=1, y=2;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; 
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

void *Thread1(void *arg)
{
    int i, tmp;
    sleep(1);
    x=2; y=1;
    if (x > y) pthread_cond_broadcast(&cond);
    printf("Thread1 End\n");
    return NULL;
}

void *Thread2(void *arg)
{
    struct timeval now;
    struct timespec timeout;
    int retcode;
    pthread_mutex_lock(&mut);
    gettimeofday(&now, NULL);
    timeout.tv_sec = now.tv_sec + 5;
    timeout.tv_nsec = now.tv_usec * 1000;
    retcode = 0;
    if(x <= y) {
        printf("Thread2 Sleep\n");
        retcode = pthread_cond_timedwait(&cond, &mut, &timeout);
    }
    if (retcode == ETIMEDOUT) {
        printf("TimeOut\n");
    } else {
        printf("x=%d, y=%d\n", x, y);
    }
    pthread_mutex_unlock(&mut);
    printf("Thread2 End\n");
    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t thread1;
    pthread_t thread2;

    pthread_create(&thread1, NULL, Thread1, NULL);
    pthread_create(&thread2, NULL, Thread2, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    
    pthread_mutex_destroy(&mut);
    pthread_cond_destroy(&cond);
    return 0;
}


